/**
 * 连续相同数的最大长度
 * https://leetcode.cn/problems/max-consecutive-ones-iii/
 */
class Solution1 {
    public int longestOnes(int[] nums, int k) {

        //1.定义滑动窗口
        int left = 0,right = 0,zero = 0,ret = 0;

        for(;right < nums.length;right++){

            //2.进窗口
            if(nums[right] == 0) zero++;//统计窗口0的个数

            //3.判断
            while(zero > k){
                //出窗口
                if(nums[left++] == 0) zero--;
            }

            //更新结果
            ret = Math.max(ret,right - left + 1);
        }
        return ret;
    }
}

/**
 * 将x不为0的最小操作数
 * https://leetcode.cn/problems/minimum-operations-to-reduce-x-to-zero/
 * 时间复杂度:O(n)
 * 空间复杂度:O(1)
 */
class Solution2 {

    public static int minOperations(int[] nums, int x) {

        int sum = 0;
        for(int i = 0;i< nums.length;i++ ){
            sum += nums[i];
        }
        int target = sum - x;
        if(target < 0) return -1;

        int left = 0,right = 0,ret = -1;
        sum = 0;
        for(;right < nums.length;right++){
            sum += nums[right];//进入窗口

            //判断
            while(sum > target)
                sum -= nums[left++];//出窗口

            if(target == sum) ret = Math.max(ret,right - left + 1);  //更新
        }

        return ret == -1 ? -1 : nums.length - ret;

    }

    public static void main(String[] args) {
        int len = Solution2.minOperations(new int[]{8828,9581,49,9818,9974,9869,9991,10000,10000,
                10000,9999,9993,9904,8819,1231,6309},134365);
        System.out.println(len);
    }
}

